<template>
  <Card class="overflow-hidden">
    <NuxtLink :to="`/item/${item.id}`">
      <div class="relative h-[200px]">
        <img v-if="imageUrl" class="h-[200px] w-full object-cover shadow-md" loading="lazy" :src="imageUrl" alt="" @error="handleImageError" />
        <!-- 原图标记 -->
        <div v-if="isShowingOriginal" class="absolute right-2 top-2">
          <Badge class="bg-orange-500 text-white hover:bg-orange-600 text-xs px-2 py-1">
            <MdiImageIcon class="size-3 mr-1" />
            原图
          </Badge>
        </div>
        <div class="absolute inset-x-1 bottom-1">
          <Badge class="text-wrap bg-secondary text-secondary-foreground hover:bg-secondary/70 hover:underline">
            <NuxtLink v-if="item.location" :to="`/location/${item.location.id}`">
              {{ locationString }}
            </NuxtLink>
          </Badge>
        </div>
      </div>
      <div class="col-span-4 flex grow flex-col gap-y-1 p-4 pt-2">
        <h2 class="line-clamp-2 text-ellipsis text-wrap text-lg font-bold">{{ item.name }}</h2>
        <Separator class="mb-1" />
        <TooltipProvider :delay-duration="0">
          <div class="flex items-center gap-2">
            <Tooltip v-if="item.insured">
              <TooltipTrigger>
                <MdiShieldCheck class="size-5 text-primary" />
              </TooltipTrigger>
              <TooltipContent>
                {{ $t("global.insured") }}
              </TooltipContent>
            </Tooltip>
            <Tooltip v-if="item.archived">
              <TooltipTrigger>
                <MdiArchive class="size-5 text-destructive" />
              </TooltipTrigger>
              <TooltipContent>
                {{ $t("global.archived") }}
              </TooltipContent>
            </Tooltip>
            <div class="grow"></div>
            <Tooltip>
              <TooltipTrigger>
                <Badge>
                  {{ item.quantity }}
                </Badge>
              </TooltipTrigger>
              <TooltipContent>
                {{ $t("global.quantity") }}
              </TooltipContent>
            </Tooltip>
          </div>
        </TooltipProvider>
        <Markdown class="mb-2 line-clamp-3 text-ellipsis" :source="item.description" />
        <div class="-mr-1 mt-auto flex flex-wrap justify-end gap-2">
          <LabelChip v-for="label in itemLabels" :key="label.id" :label="label" size="sm" />
        </div>
      </div>
    </NuxtLink>
  </Card>
</template>

<script setup lang="ts">
  import type { ItemOut, ItemSummary } from "~~/lib/api/types/data-contracts";
  import MdiShieldCheck from "~icons/mdi/shield-check";
  import MdiArchive from "~icons/mdi/archive";
  import MdiImageIcon from "~icons/mdi/image";
  import { Badge } from "@/components/ui/badge";
  import { Card } from "@/components/ui/card";
  import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
  import { Separator } from "@/components/ui/separator";
  import { onMounted } from "vue";

  const api = useUserApi();
  const emit = defineEmits(['thumbnail-generated']);

  const imageUrl = computed(() => {
    if (!props.item.imageId) {
      return "/no-image.jpg";
    }
    
    // 优先使用响应式更新的缩略图URL
    if (thumbnailUrl.value) {
      return thumbnailUrl.value;
    }
    
    // 如果该附件已标记为失败，直接使用原图
    if (failedThumbnails.value.has(props.item.imageId)) {
      return api.authURL(`/items/${props.item.id}/attachments/${props.item.imageId}`);
    }
    
    // 有缩略图ID时，直接使用缩略图ID而不是缩略图API
    if (props.item.thumbnailId) {
      return api.authURL(`/items/${props.item.id}/attachments/${props.item.thumbnailId}`);
    } else {
      // 没有缩略图，显示原图
      return api.authURL(`/items/${props.item.id}/attachments/${props.item.imageId}`);
    }
  });

  // 判断当前是否显示原图
  const isShowingOriginal = computed(() => {
    if (!props.item.imageId) {
      return false;
    }
    
    // 如果该附件已标记为失败，说明正在显示原图
    if (failedThumbnails.value.has(props.item.imageId)) {
      return true;
    }
    
    // 如果没有缩略图但有图片ID，说明显示的是原图
    if (!props.item.thumbnailId && !thumbnailUrl.value) {
      return true;
    }
    
    return false;
  });

  // 响应式缩略图URL，支持自动更新
  const thumbnailUrl = ref<string | null>(null);
  
  // 记录失败的缩略图附件ID，避免重复尝试
  const failedThumbnails = ref<Set<string>>(new Set());
  // 处理图片加载错误，自动降级到原图或默认图片
  const handleImageError = (event: Event) => {
    const img = event.target as HTMLImageElement;
    const currentUrl = img.src;
    
    // 如果是缩略图失败（包括404或400错误）
    if (props.item.imageId && (currentUrl.includes(props.item.thumbnailId || '') || currentUrl.includes('/thumbnail'))) {
      // 记录失败的附件ID
      failedThumbnails.value.add(props.item.imageId);
      // 立即切换到原图链接
      img.src = api.authURL(`/items/${props.item.id}/attachments/${props.item.imageId}`);
    }
    // 如果原图也加载失败，使用默认占位图片
    else if (currentUrl.includes('/attachments/') && !currentUrl.includes('/no-image.jpg')) {
      img.src = "/no-image.jpg";
    }
  };

  // 自动检测并生成缩略图
  onMounted(async () => {
    // 如果有图片但没有缩略图，尝试生成
    if (props.item.imageId && !props.item.thumbnailId) {
      try {
        // 获取项目详情以获取附件信息
        const { data: itemDetail } = await api.items.get(props.item.id);
        if (itemDetail && itemDetail.attachments && itemDetail.attachments.length > 0) {
          // 找到主图片附件
          const primaryAttachment = itemDetail.attachments.find(att => att.id === props.item.imageId);
          if (primaryAttachment) {
            // 调用API生成缩略图
            const result = await api.items.attachments.createThumbnail(props.item.id, primaryAttachment.id);
            
            if (result.error) {
              return;
            }
            
            // 刷新项目数据
            const { data: updatedItem } = await api.items.get(props.item.id);
            if (updatedItem && updatedItem.thumbnailId) {
              // 更新响应式缩略图URL，使用缩略图API路径
              thumbnailUrl.value = api.authURL(`/items/${props.item.id}/attachments/${props.item.imageId}/thumbnail`);
              
              // 触发父组件更新
              emit('thumbnail-generated', {
                itemId: props.item.id,
                thumbnailId: updatedItem.thumbnailId
              });
            }
          }
        }
      } catch (error) {
        // 静默失败，不影响用户体验
      }
    }
  });

  const itemLabels = computed(() => {
    return props.item.labels || [];
  });

  const props = defineProps({
    item: {
      type: Object as () => ItemOut | ItemSummary,
      required: true,
    },
    locationFlatTree: {
      type: Array as () => FlatTreeItem[],
      required: false,
      default: () => [],
    },
  });

  const locationString = computed(
    () => props.locationFlatTree.find(l => l.id === props.item.location?.id)?.treeString || props.item.location?.name
  );
</script>

<style lang="css"></style>
